<?php

/**
 * Some rights reserved：abc3210.com
 * Contact email:admin@abc3210.com
 */
//定义是否后台操作
define("isadmin", 1);

class ContentAction extends AdminbaseAction {

    public $categorys, $Content, $table_name, $fbtable_name, $Model;

    function _initialize() {
        //设置生成静态后缀为空，按URL规则生成相应后缀
        C('HTML_FILE_SUFFIX', "");
        //跳转时间
        $this->assign("waitSecond", 2000);
        import('ContentModel');
        $this->categorys = F("Category");
        $this->Model = F("Model");
        $catid = $this->_get("catid");
        if (empty($catid)) {
            $catid = $this->_post("catid");
        }
        //所有的权限 都分为 add(添加) edit(编辑) delete(删除) index(默认操作) listorder(排序) remove(移动文章) push(推送)
        //权限判断  如果方法是以 public_开头的，也不验证权限
        if (empty($_SESSION[C("ADMIN_AUTH_KEY")]) && strpos(ACTION_NAME, 'public_') === false && ACTION_NAME != "index") {
            C("USER_AUTH_ON", false);
            //操作
            $action = $this->categorys[$catid]['type'] == 0 ? ACTION_NAME : 'init';
            if ($action == "classlist") {
                $action = "init";
            }
            $priv_datas = M("Category_priv")->where(array('catid' => $catid, 'is_admin' => 1, 'roleid' => $_SESSION['roleid'], 'action' => $action))->select();
            if (!$priv_datas) {
                $this->error("您没有权限操作该项！");
            }
        } else {
            C("USER_AUTH_ON", true);
        }
        parent::_initialize();
        import('@.ORG.Util.Form');
        import('@.ORG.Util.Url');
        if (isset($_GET['catid']) && empty($this->Model[$this->categorys[$catid]['modelid']])) {
            $this->error("模型或者栏目不存在！！");
        }
        $this->url = new Url();
    }

    public function index() {
        $this->display();
    }

    /**
     * 错误提示
     * @param type $message
     * @param type $jumpUrl
     * @param type $ajax 
     */
    public function error($message, $jumpUrl = '', $ajax = false) {
        parent::error($message, $jumpUrl, $ajax);
    }

    public function buildHtml($htmlfile = '', $htmlpath = '', $templateFile = '') {
        parent::buildHtml($htmlfile, $htmlpath, $templateFile);
    }

    public function assign($name, $value = '') {
        parent::assign($name, $value);
    }

    /**
     * 显示对应栏目信息列表 
     */
    public function classlist() {
        $catid = $this->_get("catid");
        $Categorys = $this->categorys[$catid];
        $this->assign("Categorys", $Categorys);
        //是否搜索
        $search = $this->_get("search");
        $where = array();
        $where["catid"] = array("EQ", $catid);
        $Model = F("Model");
        if (!empty($Categorys)) {
            //取得主表名
            $tablename = $Model[$Categorys['modelid']]['tablename'];
            if (empty($tablename)) {
                $this->error("模型不存在！");
            }
            //检查模型是否被禁用
            if ($Model[$Categorys['modelid']]['disabled'] == 1) {
                $this->error("模型被禁用！");
            }
            $this->Content = new ContentModel(ucwords($tablename));
            //检查表是否存在
            if (!$this->Content->table_exists($tablename)) {
                $this->error("数据表不存在！");
            }
            //搜索相关开始
            if (!empty($search)) {
                //添加开始时间
                $start_time = $this->_get("start_time");
                if (!empty($start_time)) {
                    $start_time = strtotime($start_time);
                    $where["inputtime"] = array("EGT", $start_time);
                }
                //添加结束时间
                $end_time = $this->_get("end_time");
                if (!empty($end_time)) {
                    $end_time = strtotime($end_time);
                    $where["inputtime"] = array("ELT", $end_time);
                }

                if ($end_time > 0 && $start_time > 0) {
                    $where['inputtime'] = array(array('EGT', $start_time), array('ELT', $end_time));
                }

                //推荐
                $posids = $this->_get("posids");
                if (!empty($posids)) {
                    $where["posids"] = array("EQ", $posids);
                }
                //搜索字段
                $searchtype = (int) $this->_get("searchtype");
                //搜索关键字
                $keyword = Input::getVar($this->_get("keyword"));
                if (!empty($keyword)) {
                    $type_array = array('title', 'description', 'username');
                    if ($searchtype < 3) {
                        $searchtype = $type_array[$searchtype];
                        $where[$searchtype] = array("LIKE", "%" . $keyword . "%");
                    } elseif ($searchtype == 3) {
                        $where["id"] = array("EQ", (int) $keyword);
                    }
                }
            }

            //信息总数
            $count = $this->Content->where($where)->count();
            $page = $this->page($count, 20);
            $Content = $this->Content->where($where)->limit($page->firstRow . ',' . $page->listRows)->order(array("id" => "DESC"))->select();
        } else {
            $this->error("该栏目不存在！");
        }

        $this->assign("search", $search);
        $this->assign("start_time", $start_time);
        $this->assign("end_time", $end_time);
        $this->assign("posids", $posids);
        $this->assign("searchtype", $searchtype);
        $this->assign("keyword", $keyword);

        $this->assign($Categorys);
        $this->assign("count", $count);
        $this->assign("catid", $catid);
        $this->assign("Content", $Content);
        $this->assign("Page", $page->show('Admin'));
        $this->display();
    }

    /**
     * 添加信息 
     */
    public function add() {
        if ($this->isPost()) {
            //栏目ID
            $catid = $_POST['info']['catid'] = intval($_POST['info']['catid']);
            if (empty($catid)) {
                $this->error("请指定栏目ID！");
            }
            if (trim($_POST['info']['title']) == '') {
                $this->error("标题不能为空！");
            }
            //获取当前栏目配置
            $category = $this->categorys[$catid];
            //栏目类型为0
            if ($category['type'] == 0) {
                //模型ID
                $this->modelid = $modelid = $this->categorys[$catid]['modelid'];
                //setting 配置
                $setting = unserialize($category['setting']);
                if ((int) $_POST['info']['status'] != 99) {
                    //如果用户是超级管理员，那么则根据自己的设置来发布
                    $_POST['info']['status'] = $_SESSION['roleid'] == 1 ? intval($_POST['info']['status']) : 1;
                } else {
                    $_POST['info']['status'] = 99;
                }
                
                //添加数据
                $status = $this->add_content($_POST['info']);
                if ($status) {
                    $this->success("添加成功！");
                } else {
                    $this->error("添加失败！");
                }
            }
        } else {
            $catid = $this->_get("catid");
            //取得对应模型
            $category = $this->categorys[$catid];
            if (empty($category)) {
                $this->error("参数错误！");
            }
            //模型ID
            $modelid = $category['modelid'];
            //取模型ID，依模型ID来生成对应的表单
            require RUNTIME_PATH . 'content_form.class.php';
            //实例化表单类 传入 模型ID 栏目ID 栏目数组
            $content_form = new content_form($modelid, $catid, $this->categorys);
            //生成对应字段的输入表单
            $forminfos = $content_form->get();
            //生成对应的JS提示等
            $formValidator = $content_form->formValidator;
            //取得当前栏目setting配置信息
            $setting = unserialize($category['setting']);

            $workflowid = $setting['workflowid'];

            //当前登陆用户名
            $admin_username = $this->Cache["username"];
            //var_dump($category);exit;
            $this->assign("catid", $catid);
            $this->assign("uploadurl", CONFIG_SITEFILEURL);
            $this->assign("content_form", $content_form);
            $this->assign("forminfos", $forminfos);
            $this->assign("formValidator", $formValidator);
            $this->assign("setting", $setting);
            $this->assign("admin_username", $admin_username);
            $this->assign("category", $category);
            $this->assign("workflowid", $workflowid);
            $this->display();
        }
    }

    /**
     * 编辑信息 
     */
    public function edit() {
        $catid = $this->_get("catid");
        $catid = empty($catid) ? (int) $_POST['info']['catid'] : $catid;
        $id = $this->_get("id");
        $id = empty($id) ? $this->_post("id") : $id;

        if (empty($catid) || empty($id)) {
            $this->error("参数不完整！");
        }
        $Categorys = $this->categorys[$catid];
        if (empty($Categorys)) {
            $this->error("该栏目不存在！");
        }
        $this->modelid = $modelid = $Categorys['modelid'];
        //取得表名
        $this->table_name = ucwords($this->Model[$Categorys['modelid']]['tablename']);
        $this->fbtable_name = $this->table_name . "_data";
        if (empty($this->table_name)) {
            $this->error("模型不存在！");
        }
        //检查模型是否被禁用
        if ($this->Model[$Categorys['modelid']]['disabled'] == 1) {
            $this->error("模型被禁用！");
        }

        if ($this->isPost()) {
            if (trim($_POST['info']['title']) == '') {
                $this->error("标题不能为空！");
            }
            if ((int) $_POST['info']['status'] != 99) {
                //如果用户是超级管理员，那么则根据自己的设置来发布
                $_POST['info']['status'] = $_SESSION['roleid'] == 1 ? intval($_POST['info']['status']) : 1;
            } else {
                $_POST['info']['status'] = 99;
            }
            $status = $this->edit_content($_POST['info'], $id);
            if ($status) {
                $this->success("修改成功！<script>setTimeout(function(){window.close();},1000);</script>");
            } else {
                $this->error("修改失败！");
            }
        } else {
            $this->Content = new ContentModel($this->table_name);
            //检查表是否存在
            if (!$this->Content->table_exists(strtolower($this->table_name))) {
                $this->error("数据表不存在！");
            }
            //取得数据，这里使用关联查询
            $data = $this->Content->relation(true)->where(array("id" => $id))->find();
            if (!$data) {
                $this->error("该信息不存在！");
            }
            //数据处理，把关联查询的结果集合并
            $datafb = $data[$this->fbtable_name];
            unset($data[$this->fbtable_name]);
            $data = array_merge($data, $datafb);

            //引入输入表单处理类
            require RUNTIME_PATH . 'content_form.class.php';
            $content_form = new content_form($modelid, $catid, $this->categorys);
            //字段内容
            $forminfos = $content_form->get($data);
            //js提示
            $formValidator = $content_form->formValidator;

            $this->assign("data", $data);
            $this->assign("catid", $catid);
            $this->assign("id", $id);
            $this->assign("uploadurl", CONFIG_SITEFILEURL);
            $this->assign("content_form", $content_form);
            $this->assign("forminfos", $forminfos);
            $this->assign("formValidator", $formValidator);
            $this->display();
        }
    }

    /**
     * 删除 
     */
    public function delete() {
        if (isset($_GET['dosubmit'])) {
            $catid = (int) $this->_get("catid");
            if (!$catid) {
                $this->error("缺少栏目ID！");
            }
            if (empty($_POST['ids'])) {
                $this->error("没有信息被选中！");
            }
            //模型ID
            $this->modelid = $modelid = $this->categorys[$catid]['modelid'];
            //是否生成HTML
            $sethtml = $this->categorys[$catid]['sethtml'];
            //栏目配置信息
            $setting = unserialize($this->categorys[$catid]['setting']);
            $content_ishtml = $setting['content_ishtml'];
            $this->table_name = ucwords($this->Model[$this->modelid]['tablename']);
            $this->Content = new ContentModel($this->table_name);
            foreach ($_POST['ids'] as $id) {
                $r = $this->Content->where(array("id" => $id))->find();
                if ($content_ishtml && !$r['islink']) {
                    $urls = $this->deleteHtml($r['catid'], $id, $r['inputtime'], $r['prefix']);
                } else {
                    $fileurl = 0;
                }
                //删除内容
                $this->delete_content($id, $catid, $fileurl);
                //删除附件
                import('@.ORG.Util.Attachment');
                $Attachment = new Attachment();
                $Attachment->api_delete('c-' . $catid . '-' . $id);
            }

            $this->success("删除成功！");
        } else {
            $this->error("操作失败！");
        }
    }

    /**
     * 删除内容
     * @param $id 内容id
     * @param $catid 栏目id
     * @param $file 文件路径
     */
    protected function delete_content($id, $catid, $file = '') {
        //删除数据
        $this->Content->relation(true)->where(array('id' => $id))->delete();
        //删除统计
        M("Hits")->where(array("hitsid" => "c-" . $catid . "-" . $id))->delete();
        //删除评论
        import('@.ORG.Util.Comment');
        $Comment = new Comment();
        $comment_id = "c-$catid-$id";
        $Comment->deletecommentid($comment_id);
        //删除推荐位
        M("Position_data")->where(array("id" => $id, "catid" => $catid, "module" => "content"))->delete();
    }

    /**
     * 排序 
     */
    public function listorder() {
        
    }

    /**
     * 快速进入搜索
     */
    public function public_ajax_search() {
        if ($_GET['catname']) {
            if (preg_match('/([a-z]+)/i', $_GET['catname'])) {
                $field = 'letter';
                $catname = strtolower(trim($_GET['catname']));
            } else {
                $field = 'catname';
                $catname = trim($_GET['catname']);
            }
            $where = array();
            $where[$field] = array("LIKE", $catname . "%");
            $where['child'] = array("EQ", 0);
            $Category = M("Category");
            $data = $Category->where($where)->limit(10)->getField("catid,catid,type,catname,letter");

            echo json_encode($data);
        }
    }

    /**
     * 显示栏目菜单列表 
     */
    public function public_categorys() {
        import('@.ORG.Util.Tree');
        $tree = new Tree();
        //栏目权限 超级管理员例外
        if (empty($_SESSION[C("ADMIN_AUTH_KEY")])) {
            $role_id = $this->Cache['User']['role_id'];
            $priv_result = M("Category_priv")->where(array("roleid" => $role_id, 'action' => 'init'))->select();
            $priv_catids = array();
            foreach ($priv_result as $_v) {
                $priv_catids[] = $_v['catid'];
            }
        }
        if (!empty($this->categorys)) {
            foreach ($this->categorys as $r) {
                if ($r['type'] == 2 && $r['child'] == 0)
                    continue;
                //只显示有init权限的，超级管理员除外
                if (empty($_SESSION[C("ADMIN_AUTH_KEY")]) && !in_array($r['catid'], $priv_catids)) {
                    $arrchildid = explode(',', $r['arrchildid']);
                    $array_intersect = array_intersect($priv_catids, $arrchildid);
                    if (empty($array_intersect))
                        continue;
                }
                $r['icon_type'] = $r['vs_show'] = '';
                $r['type'] = 'classlist';
                $r['add_icon'] = "<a target='right' href='?g=Contents&m=Content&a=classlist&catid=" . $r['catid'] . "' onclick=javascript:openwinx('" . U("Contents/Content/add", array("catid" => $r['catid'])) . "','')><img src='" . $this->Cache['Config']['siteurl'] . "statics/images/add_content.gif' alt='添加'></a> ";
                $categorys[$r['catid']] = $r;
            }
        }
        //var_dump($categorys);exit;
        if (!empty($categorys)) {
            $tree->init($categorys);
            $strs = "<span class='\$icon_type'>\$add_icon<a href='?g=Contents&m=Content&a=\$type&catid=\$catid' target='right' >\$catname</a></span>";
            $strs2 = "<span class='folder'>\$catname</span>";
            $categorys = $tree->get_treeview(0, 'category_tree', $strs, $strs2, $ajax_show);
        } else {
            $categorys = "该站点下面还没有栏目，请先添加栏目";
        }
        $this->assign("categorys", $categorys);
        $this->display();
    }

    /**
     * 检测标题是否存在 
     */
    public function public_check_title($title = "", $catid = "") {
        $title = $title == "" ? $this->_get('data') : $title;
        $catid = $catid == "" ? $this->_get('catid') : $catid;
        if (empty($title)) {
            $this->ajaxReturn("", "标题没有重复！", true);
            exit;
        }
        $Cat = F("Category");
        $Model = F("Model");
        $tablename = ucwords($Model[$Cat[$catid]['modelid']]['tablename']);
        unset($Cat);
        unset($Model);
        $count = M($tablename)->where(array("title" => $title))->count();
        if ($count > 0) {
            $this->ajaxReturn("", "标题有重复！", false);
        } else {
            $this->ajaxReturn("", "标题没有重复！", true);
        }
    }

    /*
     *  相关文章选择
     */

    public function public_relationlist() {

        $show_header = '';
        $this->Model = F("Model");
        if (!isset($_GET['modelid'])) {
            $this->error("缺少参数！");
        } else {
            $modelid = intval($_GET['modelid']);
            $this->table_name = ucwords($this->Model[$modelid]['tablename']);
            $this->Content = M($this->table_name);
            $where = array();
            if ($_GET['catid']) {
                $catid = intval($_GET['catid']);
                $where['catid'] = array('eq', $catid);
            }

            $where['status'] = array('eq', 99);

            if (isset($_GET['keywords'])) {
                $keywords = trim($_GET['keywords']);
                $field = $_GET['field'];
                if (in_array($field, array('id', 'title', 'keywords', 'description'))) {
                    if ($field == 'id') {
                        $where['id'] = array('eq', $keywords);
                    } else {
                        $where[$field] = array('like', '%' . $keywords . '%');
                    }
                }
            }
            $count = $this->Content->where($where)->count();
            $page = $this->page($count, 12);
            $data = $this->Content->where($where)->limit($page->firstRow . ',' . $page->listRows)->order(array("id" => "DESC"))->select();

            foreach ($data as $k => $v) {
                $data[$k]['catid'] = $this->categorys[$data[$k]['catid']]['catname'];
                $data[$k]['inputtime'] = date('Y-m-d', $data[$k]['inputtime']);
            }
            $this->assign("Formcategory", Form::select_category($catid, 'name="catid"', "不限栏目", $modelid, 0, 1));
            $this->assign("data", $data);
            $this->assign("page", $page);
            $this->assign("modelid", $modelid);
            $this->display("relationlist");
        }
    }

    /**
     * 文章预览 
     */
    public function public_preview() {
        
    }

    /*
     * 审核所有内容
     */

    public function public_checkall() {
        
    }

    /**
     * 图片裁减 
     */
    public function public_imagescrop() {
        $picurl = $this->_get("picurl");
        $catid = $this->_get("catid");
        $module = $this->_get("module");
        $this->assign("picurl", $picurl);
        $this->assign("catid", $catid);
        $this->assign("module", $module);

        $this->display("imagescrop");
    }

    public function public_getsite_categorys() {
        $catid = $this->_get("catid");
        $models = F("Model");
        import('@.ORG.Util.Tree');
        $tree = new Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $categorys = array();
        if (empty($_SESSION[C("ADMIN_AUTH_KEY")])) {
            $this->priv_db = M("Category_priv");
            $priv_result = $this->priv_db->where(array('action' => 'add', 'roleid' => $_SESSION['roleid'], 'is_admin' => 1))->select();
            $priv_catids = array();
            foreach ($priv_result as $_v) {
                $priv_catids[] = $_v['catid'];
            }
            if (empty($priv_catids))
                return '';
        }

        foreach ($this->categorys as $r) {
            if ($r['siteid'] != $siteid || $r['type'] != 0)
                continue;
            if ($_SESSION['roleid'] != 1 && !in_array($r['catid'], $priv_catids)) {
                $arrchildid = explode(',', $r['arrchildid']);
                $array_intersect = array_intersect($priv_catids, $arrchildid);
                if (empty($array_intersect))
                    continue;
            }
            $r['modelname'] = $models[$r['modelid']]['name'];
            $r['style'] = $r['child'] ? 'color:#8A8A8A;' : '';
            $r['click'] = $r['child'] ? '' : "onclick=\"select_list(this,'" . safe_replace($r['catname']) . "'," . $r['catid'] . ")\" class='cu' title='" . L('click_to_select') . "'";
            $categorys[$r['catid']] = $r;
        }
        $str = "<tr \$click >
					<td align='center'>\$id</td>
					<td style='\$style'>\$spacer\$catname</td>
					<td align='center'>\$modelname</td>
				</tr>";
        $tree->init($categorys);
        $categorys = $tree->get_tree(0, $str);
        echo $categorys;
    }

    /**
     * 加载相关文章列表 
     */
    public function public_getjson_ids() {
        $this->modelid = $this->_get("modelid");
        $id = $this->_get("id");
        $this->Model = F("Model");
        $this->table_name = $this->Model[$this->modelid]['tablename'];
        if (empty($this->table_name)) {
            $this->ajaxReturn("", "", false);
            exit;
        }
        $this->Content = M(ucwords($this->table_name . "_data"));

        $r = $this->Content->where(array("id" => $id))->find();
        $this->Content = NULL;
        $where = array();
        if ($r['relation']) {
            $relation = str_replace('|', ',', $r['relation']);
            $where['id'] = array("in", $relation);
            $this->Content = M(ucwords($this->table_name));
            $datas = $this->Content->where($where)->select();
            foreach ($datas as $_v) {
                $_v['sid'] = 'v' . $_v['id'];
                $infos[] = $_v;
            }
        }
        unset($this->Content);
        unset($datas);
        $this->ajaxReturn($infos, "", true);
    }

    /*
     * 批量移动文章
     */

    public function remove() {
        
    }

    /**
     * 同时发布到其他栏目 
     */
    public function add_othors() {
        $catid = $this->_get("catid");
        if (!empty($catid)) {
            $this->assign("catid", $catid);
        }
        $this->display();
    }

    /**
     * 添加内容 
     */
    protected function add_content($data, $isimport = 0) {
        import('@.ORG.Util.Html');
        $html = new Html();
        $html->pointer($this);

        require RUNTIME_PATH . 'content_input.class.php';
        require RUNTIME_PATH . 'content_update.class.php';

        $content_input = new content_input($this->modelid, $this);
        $inputinfo = $content_input->get($data, $isimport);

        if (is_bool($inputinfo) && $inputinfo == false) {
            $this->error("数据处理出现错误！");
        }

        //主表字段内容
        $systeminfo = $inputinfo['system'];
        //副表字段内容
        $modelinfo = $inputinfo['model'];

        //检查发表时间，如果有时间转换为时间戳
        if ($data['inputtime'] && !is_numeric($data['inputtime'])) {
            $systeminfo['inputtime'] = strtotime($data['inputtime']);
        } elseif (!$data['inputtime']) {
            $systeminfo['inputtime'] = time();
        } else {
            $systeminfo['inputtime'] = $data['inputtime'];
        }
        //读取模型字段配置中，关于日期配置格式，来组合日期数据
        $this->fields = F("Model_field_" . $this->modelid);
        $setting = unserialize($this->fields['inputtime']['setting']);
        //从数组中把变量导入到当前的符号表中
        extract($setting);
        if ($fieldtype == 'date') {
            $systeminfo['inputtime'] = date('Y-m-d');
        } elseif ($fieldtype == 'datetime') {
            $systeminfo['inputtime'] = date('Y-m-d H:i:s');
        }

        //更新时间处理
        if ($data['updatetime'] && !is_numeric($data['updatetime'])) {
            $systeminfo['updatetime'] = strtotime($data['updatetime']);
        } elseif (!$data['updatetime']) {
            $systeminfo['updatetime'] = time();
        } else {
            $systeminfo['updatetime'] = $data['updatetime'];
        }

        //添加用户名
        $systeminfo['username'] = $data['username'] ? $data['username'] : $this->Cache['username'];
        //标识是否后台发布
        $systeminfo['sysadd'] = defined('IN_ADMIN') ? 1 : 0;

        //自动提取摘要，如果有设置自动提取，且description为空，且有内容字段才执行
        if (isset($_POST['add_introduce']) && $systeminfo['description'] == '' && isset($modelinfo['content'])) {
            $content = stripslashes($modelinfo['content']);
            $introcude_length = intval($_POST['introcude_length']);
            $systeminfo['description'] = str_cut(str_replace(array("\r\n", "\t", '[page]', '[/page]', '&ldquo;', '&rdquo;', '&nbsp;'), '', strip_tags($content)), $introcude_length);
            $inputinfo['system']['description'] = $systeminfo['description'] = Input::getVar($systeminfo['description']);
        }

        //自动提取缩略图，从content 中提取
        if (isset($_POST['auto_thumb']) && $systeminfo['thumb'] == '' && isset($modelinfo['content'])) {
            $content = $content ? $content : stripslashes($modelinfo['content']);
            $auto_thumb_no = intval($_POST['auto_thumb_no']) - 1;
            if (preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
                $systeminfo['thumb'] = $matches[3][$auto_thumb_no];
            }
        }

        //主表操作开始
        $this->table_name = ucwords($this->Model[$this->modelid]['tablename']);
        $this->fbtable_name = $this->table_name . "_data";
        $this->Content = new ContentModel($this->table_name);
        //使用TP的自动验证，所以要把令牌合并
        $systeminfo = array_merge($systeminfo, array(C("TOKEN_NAME") => $_POST[C("TOKEN_NAME")]));

        $status = $this->Content->create($systeminfo);
        if (!$status) {
            $this->error($this->Content->getError());
        }

        //把副表的数据合并，按关联模型的需求合并
        $fdata = array(
            $this->fbtable_name => $modelinfo
        );
        $status = array_merge($status, $fdata);
        //插入成功返回ID
        $id = $modelinfo['id'] = $this->Content->relation(true)->data($status)->add();

        if (is_bool($id) && $id == false) {
            $this->error("信息录入失败！");
        }

        //转向地址
        if ($data['islink'] == 1) {
            $urls[0] = $_POST['linkurl'];
        } else {
            //生成该篇地址
            $urls = $this->url->show($id, 0, $systeminfo['catid'], $systeminfo['inputtime'], $data['prefix'], $inputinfo, 'add');
        }
        //更新url
        $this->Content->where(array('id' => $id))->data(array('url' => $urls[0]))->save();
        //添加统计
        $this->hits_db = M("Hits");
        $hitsid = 'c-' . $systeminfo['catid'] . '-' . $id;
        $this->hits_db->add(array('hitsid' => $hitsid, 'catid' => $systeminfo['catid'], 'updatetime' => time()), array(), true);

        //调用 update
        $content_update = new content_update($this->modelid, $this, $id);
        //合并后，调用update
        $merge_data = array_merge($systeminfo, $modelinfo);
        $merge_data['posids'] = $data['posids'];
        $merge_data['url'] = $urls[0];
        $content_update->update($merge_data);

        //发布到其他栏目
        if ($id && isset($_POST['othor_catid']) && is_array($_POST['othor_catid'])) {
            //原篇地址
            $linkurl = $urls[0];
            //循环需要同步发布的栏目
            foreach ($_POST['othor_catid'] as $cid => $_v) {
                //获取需要同步栏目所属模型ID
                $mid = $this->categorys[$cid]['modelid'];
                //判断模型是否相同
                if ($this->modelid == $mid) {//相同
                    $inputinfo['system']['catid'] = $status['catid'] = $cid;
                    $newid = $modelinfo['id'] = $this->Content->relation(true)->data($status)->add();
                    //更新URL地址
                    if ($data['islink'] == 1) {
                        $nurls = $_POST['linkurl'];
                    } else {
                        $nurls = $this->url->show($newid, 0, $cid, $systeminfo['inputtime'], $data['prefix'], $inputinfo, 'add');
                    }
                    $this->Content->where(array('id' => $newid))->data(array('url' => $nurls[0]))->save();
                    if ($urls['content_ishtml'] && $data['status'] == 99) {
                        $html->show($nurls[1], $nurls['data']);
                    }
                } else {//不相同
                    //不同模型，则以链接的形式添加，也就是转向地址
                    $dataarray = array('title' => $systeminfo['title'],
                        'style' => $systeminfo['style'],
                        'thumb' => $systeminfo['thumb'],
                        'keywords' => $systeminfo['keywords'],
                        'description' => $systeminfo['description'],
                        'status' => $systeminfo['status'],
                        'catid' => $cid,
                        'url' => $linkurl,
                        'sysadd' => 1,
                        'username' => $systeminfo['username'],
                        'inputtime' => $systeminfo['inputtime'],
                        'updatetime' => $systeminfo['updatetime'],
                        'islink' => 1
                    );
                    $table_name = ucwords($this->Model[$mid]['tablename']);
                    $fdata = array(
                        $table_name . "_data" => array()
                    );
                    $dataarray = array_merge($dataarray, $fdata);
                    $Content = new ContentModel($table_name);
                    $newid = $Content->relation(true)->data($dataarray)->add();
                }
                //添加统计
                $hitsid = 'c-' . $cid . '-' . $newid;
                $this->hits_db->add(array('hitsid' => $hitsid, 'catid' => $cid, 'updatetime' => time()), array(), true);
            }
        }

        //更新附件状态，把相关附件和文章进行管理
        $this->attachment_db = D("Attachment");
        $this->attachment_db->api_update('', 'c-' . $systeminfo['catid'] . '-' . $id, 2);

        //生成静态
        if ($urls['content_ishtml'] && $data['status'] == 99) {
            //引用传递this
            $html->pointer($this);
            $html->show($urls[1], $urls['data']);
            //刷新上下篇
            $this->related_content($systeminfo['catid'], $id, "add");
            //刷新首页
            //刷新相关栏目页(前6页)
        }

        return true;
    }

    /**
     * 修改内容 
     */
    protected function edit_content($data, $id) {
        require RUNTIME_PATH . 'content_input.class.php';
        require RUNTIME_PATH . 'content_update.class.php';
        //主表操作开始
        $this->table_name = ucwords($this->Model[$this->modelid]['tablename']);
        $this->fbtable_name = $this->table_name . "_data";
        $this->Content = new ContentModel($this->table_name);
        
        $content_input = new content_input($this->modelid, $this);
        $inputinfo = $content_input->get($data);

        //主表字段内容
        $systeminfo = $inputinfo['system'];
        //副表字段内容
        $modelinfo = $inputinfo['model'];

        //取得inputtime的真实发布时间
       //inputtime为真实发表时间，不允许修改
        if(!$systeminfo['inputtime']){
            $systeminfo['inputtime'] = $inputtime = $this->Content->where(array("id"=>$id))->getField("inputtime");
        }

        //更新时间处理
        if ($data['updatetime'] && !is_numeric($data['updatetime'])) {
            $systeminfo['updatetime'] = strtotime($data['updatetime']);
        } elseif (!$data['updatetime']) {
            $systeminfo['updatetime'] = time();
        } else {
            $systeminfo['updatetime'] = $data['updatetime'];
        }
        
        //自动提取摘要，如果有设置自动提取，且description为空，且有内容字段才执行
        if (isset($_POST['add_introduce']) && $systeminfo['description'] == '' && isset($modelinfo['content'])) {
            $content = stripslashes($modelinfo['content']);
            $introcude_length = intval($_POST['introcude_length']);
            $systeminfo['description'] = str_cut(str_replace(array("\r\n", "\t", '[page]', '[/page]', '&ldquo;', '&rdquo;', '&nbsp;'), '', strip_tags($content)), $introcude_length);
            $inputinfo['system']['description'] = $systeminfo['description'] = Input::getVar($systeminfo['description']);
        }

        //自动提取缩略图，从content 中提取
        if (isset($_POST['auto_thumb']) && $systeminfo['thumb'] == '' && isset($modelinfo['content'])) {
            $content = $content ? $content : stripslashes($modelinfo['content']);
            $auto_thumb_no = intval($_POST['auto_thumb_no']) - 1;
            if (preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
                $systeminfo['thumb'] = $matches[3][$auto_thumb_no];
            }
        }

        //转向地址
        if ($data['islink'] == 1) {
            $systeminfo['url'] = $_POST['linkurl'];
        } else {
            //生成该篇地址
            $urls = $this->url->show($id, 0, $systeminfo['catid'], $inputtime, $data['prefix'], $inputinfo, 'edit');
            $systeminfo['url'] = $urls[0];
        }
        
        //使用TP的自动验证，所以要把令牌合并
        $systeminfo = array_merge($systeminfo, array(C("TOKEN_NAME") => $_POST[C("TOKEN_NAME")]));

        $status = $this->Content->create($systeminfo);
        if (!$status) {
            $this->error($this->Content->getError());
        }
        
        //把副表的数据合并，按关联模型的需求合并
        $status['id'] = $id;
        $fdata = array(
            $this->fbtable_name => $modelinfo
        );
        $status = array_merge($status, $fdata);
        //删除真实时间的信息，避免被更新
        unset($status['inputtime']);
        //数据修改，这里使用关联操作
        $this->Content->relation(true)->where(array('id' => $id))->save($status);

        //调用 update
        $content_update = new content_update($this->modelid, $this, $id);
        $data['url'] = $systeminfo['url'];
        $content_update->update($data);

        //更新附件状态，把相关附件和文章进行管理
        $this->attachment_db = D("Attachment");
        $this->attachment_db->api_update('', 'c-' . $systeminfo['catid'] . '-' . $id, 2);

        //生成静态
        import('@.ORG.Util.Html');
        if ($urls['content_ishtml'] && $data['status'] == 99) {
            $html = new Html();
            //引用传递this
            $html->pointer($this);
            $html->show($urls[1], $urls['data']);
            //刷新上下篇
            $this->related_content($systeminfo['catid'], $id);
        } else {
            //如果是未审核，删除已经生成
            if ($urls['content_ishtml'] && !$data['islink']) {
                $this->deleteHtml($data['catid'], $id, $systeminfo['inputtime'],$systeminfo['prefix']);
            }
        }

        return true;
    }

    /**
     * 删除生成静态的文章文件 
     */
    protected function deleteHtml($catid, $id, $inputtime ,$prefix = '') {
        import('@.ORG.Util.Url');
        $url = new Url();
        //获取信息生成地址和url
        $urls = $url->show($id, 0, $catid, $inputtime,$prefix);
        $fileurl = $urls[1];
        //删除静态文件
        $lasttext = strrchr($fileurl, '.');
        $len = -strlen($lasttext);
        $path = substr($fileurl, 0, $len);
        $path = ltrim($path, '/');
        $filelist = glob(SITE_PATH . "/" . $path . '*');
        foreach ($filelist as $delfile) {
            $lasttext = strrchr($delfile, '.');
            if (!in_array($lasttext, array('.htm', '.html', '.shtml')))
                continue;
            @unlink($delfile);
        }
        return $urls;
    }

    /**
     * 上下篇生成
     * @param type $catid
     * @param type $id 
     */
    public function related_content($catid, $id, $action = "edit") {
        if (!$catid || !$id) {
            return;
        }

        $categorys = F("Category");
        $Model = F("Model");
        $modelid = $categorys[$catid]['modelid'];

        $tabname = $Model[$modelid]['tablename'];
        $db = M(ucwords($tabname));
        $where = array();
        $where['status'] = array("EQ", "99");
        $where['id'] = array("LT", $id);
        $data[] = $db->where($where)->order(array("id" => "DESC"))->find();
        if ($action == "edit") {
            $where['id'] = array("GT", $id);
            $data[] = $db->where($where)->find();
        }
        $db = NULL;
        import('@.ORG.Util.Html');
        import('@.ORG.Util.Url');
        $html = new Html();
        $html->pointer($this);
        $url = new Url();

        foreach ($data as $r) {
            if ($r['islink'] || empty($r['id']))
                continue;
            $setting = unserialize($categorys[$r['catid']]['setting']);
            $content_ishtml = $setting['content_ishtml'];
            if (!$content_ishtml) {
                continue;
            }
            $fdb = M(ucwords($tabname) . "_data");
            $r2 = $fdb->where(array('id' => $r['id']))->find();
            if ($r2)
                $r = array_merge($r, $r2);
            $urls = $url->show($r['id'], 0, $r['catid'], $r['inputtime']);
            $html->show($urls[1], $r, 0, 'edit');
            $fdb = NULL;
        }

        $html = NULL;
        $url = NULL;
        return true;
    }

}

?>